#include <stdio.h>
#include <string.h>
#include "freertos.h"
#include "FreeRTOS.h"
#include "task.h"
#include "gpio.h"
#include "ff.h"
#include "fatfs.h"
#include "Steppermotor.h"


void FreeRTOS_Initialization(void)
{
  xTaskCreate((TaskFunction_t)vUserTask00,"vUserTask00",128,NULL,1,NULL);
  xTaskCreate((TaskFunction_t)vUserTask01,"vUserTask01",512,NULL,1,NULL);
  xTaskCreate((TaskFunction_t)vUserTask02,"vUserTask02",512,NULL,2,NULL);
}

void vUserTask00(void *parameter)
{
  while(1){
    vTaskDelay(500);
    LED0=LOW;
    LED1=HIGH;
    vTaskDelay(500);
    LED0=HIGH;
    LED1=LOW;
  }
}

void vUserTask01(void *parameter)
{
  TCHAR *path="0:";
  FATFS *fs=(FATFS*)pvPortMalloc(sizeof(FATFS));
  FIL *fp=(FIL*)pvPortMalloc(sizeof(FIL));
  u8 *readStr=(u8*)pvPortMalloc(0xFF);
  UINT brw;
  if(fs!=NULL&&fp!=NULL&&readStr!=NULL){
    memset(fs,0x00,sizeof(FATFS));
    memset(fp,0x00,sizeof(FIL));
    memset(readStr,0x00,0xFF);
    f_mount(fs,path,1);
    FATFS_GetFreeSpace(path);
    FATFS_Scan_Files(path);
    f_open(fp,"0:/Hello_World.txt",FA_READ);
    f_read(fp,readStr,20,&brw);
  }else{
    printf("Malloc Error\n");
  }
  f_close(fp);
  vPortFree(fs);
  vPortFree(fp);
  vPortFree(readStr);
  Start_Motor_S(1,M1_CLOCKWISE,200*200000);
	while(motor1.running==1);
  vTaskDelete(NULL);
}

void vUserTask02(void *parameter)
{
  printf("Task02\n");
  while (1){
    vTaskDelay(1000);
  }
}